package com.villaday.idf.custom.pop;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.villaday.idf.AppContext;
import com.villaday.idf.R;
import com.villaday.idf.adapter3.VipDynamicListAdapter;
import com.villaday.idf.base.BaseFragment;
import com.villaday.idf.custom.LoadingSaveDialog;
import com.villaday.idf.model3.AllPostersEntity;
import com.villaday.idf.util.BitMapUtil;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.ShareUtilse;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import byc.imagewatcher.ImageWatcher;
import razerdp.basepopup.BasePopupWindow;

import static android.content.Context.CLIPBOARD_SERVICE;

public class SharePop extends BasePopupWindow implements ImageWatcher.OnPictureLongPressListener, VipDynamicListAdapter.Callback {
    private Handler mHandler;
    private Fragment fragment;
    private Context context;
    private Activity activity;
    public static int i = 0;
    Gson gson = new GsonBuilder().create();
    private static String xcXimageFileName = "";
    public static String IMAGE_NAME = "share_all_style";
    private VipDynamicListAdapter.Callback mCallback;
    private final ImageWatcher vImageWatcher;


    public SharePop(final BaseFragment fragment, final Context context, final Activity activity, final AllPostersEntity.BodyBean body) {
        super(context);
        this.fragment = fragment;
        this.context = context;
        this.activity = activity;
        mHandler = new Handler();
        buildAnima();
        setBackground(0);
        setOutSideDismiss(true);
        setKeepSize(true);
        setPopupFadeEnable(false);
        setBackgroundColor(Color.parseColor("#B3000000"));
        setBlurBackgroundEnable(true);
        boolean isTranslucentStatus = false;
        setPictureClickCallback(this);
        vImageWatcher = ImageWatcher.Helper.with(activity) // 一般来讲， ImageWatcher 需要占据全屏的位置
                .setTranslucentStatus(!isTranslucentStatus ? Utils.calcStatusBarHeight(getContext()) : 0) // 如果是透明状态栏，你需要给ImageWatcher标记 一个偏移值，以修正点击ImageView查看的启动动画的Y轴起点的不正确
                .setErrorImageRes(R.mipmap.error_picture) // 配置error图标 如果不介意使用lib自带的图标，并不一定要调用这个API
                .setHintMode(ImageWatcher.POINT)//设置指示器（默认小白点）
                .setHintColor(context.getResources().getColor(R.color.colorRed), context.getResources().getColor(R.color.colorWhite))//设置指示器颜色
                .setOnPictureLongPressListener(this) // 长按图片的回调，你可以显示一个框继续提供一些复制，发送等功能
                .setLoader(new ImageWatcher.Loader() {//调用show方法前，请先调用setLoader 给ImageWatcher提供加载图片的实现
                    @Override
                    public void load(Context context, String url, final ImageWatcher.LoadCallback lc) {
                        Glide.with(context).asBitmap().load(url).into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                lc.onResourceReady(resource);
                            }

                            @Override
                            public void onLoadStarted(Drawable placeholder) {
                                lc.onLoadStarted(placeholder);
                            }

                            @Override
                            public void onLoadFailed(Drawable errorDrawable) {
                                lc.onLoadFailed(errorDrawable);
                            }
                        });
                    }
                })
                .create();

        fragment.mRxManager.post("sharepop", vImageWatcher);

        findViewById(R.id.tv_cancle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        TextView tv_title = findViewById(R.id.tv_title);
        tv_title.setText(body.getTitle());
        final List<String> imgs = new ArrayList<>();
        for (int i = 0; i < body.getPosterList().size(); i++) {
            imgs.add(body.getPosterList().get(i).getUrl());
        }
        findViewById(R.id.tv_text).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//复制文字+链接
                ClipboardManager mClipboardManager = mClipboardManager =
                        (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);

                ClipData mClipData;
                mClipData = ClipData.newPlainText("test", body.getDescription());
                mClipboardManager.setPrimaryClip(mClipData);
                ToastUtil.initToast(activity, "复制成功，快去转发吧");
            }
        });
        findViewById(R.id.tv_line).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//转发链接
                if (imgs == null || imgs.size() == 0) {
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        saveImageToSdCardXCX(getContext(), body.getPosterList().get(0).getUrl());

                        shareXText(0, body);
                    }
                }
                ).start();

            }
        });
        RequestOptions options = new RequestOptions()
                .placeholder(R.drawable.ic_replace)
                .error(R.drawable.ic_replace)
                .priority(Priority.HIGH);


        ImageView sdv = findViewById(R.id.sdv);
        Glide.with(context).load(body.getPoster())
                .apply(options)
                .into(sdv);
        sdv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//查看图片
                if (imgs == null || imgs.size() == 0) {
                    return;
                }
                List<ImageView> imageViews = new ArrayList<>();
                imageViews.add((ImageView) v);
                final List<String> imgs_look = new ArrayList<>();
                if (!TextUtils.isEmpty(body.getInvitePoster())) {
                    imgs_look.add(body.getInvitePoster());
                }
                if (imgs.size()>1){
                    imgs_look.add(imgs.get(imgs.size()-1));
                    for (int i = 0; i <imgs.size()-1 ; i++) {
                        imgs_look.add(imgs.get(i));
                    }

                }else {
                    for (int i = 0; i <imgs.size() ; i++) {
                        imgs_look.add(imgs.get(i));
                    }
                }
                mCallback.onThumbPictureClick(0, (ImageView) v, imageViews, imgs_look);

            }
        });

        findViewById(R.id.tv_down).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//下载海报
                if (imgs == null || imgs.size() == 0) {
                    return;
                }
                ClipboardManager mClipboardManager = mClipboardManager =
                        (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);

                ClipData mClipData;
                mClipData = ClipData.newPlainText("test", body.getDescription());
                mClipboardManager.setPrimaryClip(mClipData);
                ToastUtil.initToast(activity, "海报已保存到相册，文案已复制。");


                List<String> urls = new ArrayList<>();
                urls.addAll(imgs);
                if (!TextUtils.isEmpty(body.getInvitePoster())) {
                    urls.add(body.getInvitePoster());
                }

                LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("已保存" + (1) + "/" + urls.size() + "张");
                loadingDialog.show(activity.getFragmentManager(), "0");
                saveImageForRecursive(urls, urls.size(), loadingDialog);
            }
        });
        findViewById(R.id.tv_zhuanfa).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//转发海报
                if (imgs == null || imgs.size() == 0) {
                    return;
                }
                ClipboardManager mClipboardManager = mClipboardManager =
                        (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);

                ClipData mClipData;
                mClipData = ClipData.newPlainText("test", body.getDescription());
                mClipboardManager.setPrimaryClip(mClipData);
                ToastUtil.initToast(activity, "文案已复制");

                LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("");
                loadingDialog.show(activity.getFragmentManager(), "1");
                // 0分享给微信好友  1分享到朋友圈
                ShareUtilse.shareImage(loadingDialog, getContext(), 0, imgs, imgs.get(imgs.size() - 1),body.getDescription());

            }
        });
        findViewById(R.id.tv_faquan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//一键发圈
                if (body == null || TextUtils.isEmpty(body.getInvitePoster())) {
                    return;
                }
                ClipboardManager mClipboardManager = mClipboardManager =
                        (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);

                ClipData mClipData;
                mClipData = ClipData.newPlainText("test", body.getDescription());
                mClipboardManager.setPrimaryClip(mClipData);
                ToastUtil.initToast(activity, "文案已复制，批量发多张请下载海报。");




                LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("");
                loadingDialog.show(activity.getFragmentManager(), "1");
                //0分享给微信好友  1分享到朋友圈
                ArrayList strings = new ArrayList<>();
                strings.add(body.getPoster());
                ShareUtilse.shareImage(loadingDialog,getContext(), 1, strings, body.getPoster(),body.getDescription());

            }
        });
        findViewById(R.id.tv_share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//分享产品
               /* if (imgs == null || imgs.size() == 0) {
                    return;
                }
                final LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("");
                loadingDialog.show(activity.getFragmentManager(), "1");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        saveImageToSdCardXCX(getContext(), body.getPosterList().get(0).getUrl());

                        shareXCX(body.getShare());
                        if (loadingDialog != null) {
                            loadingDialog.dismiss();
                        }
                    }
                }
                ).start();*/

                if (body == null || TextUtils.isEmpty(body.getInvitePoster())) {
                    return;
                }



                LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("");
                loadingDialog.show(activity.getFragmentManager(), "1");
                ArrayList strings = new ArrayList<>();
                strings.add(body.getInvitePoster());
                ShareUtilse.shareImage(loadingDialog, getContext(), 0, strings, body.getInvitePoster(), body.getDescription());



            }
        });


    }

    /*public ImageWatcher getImageWatcher() {
        return vImageWatcher;
    }
*/
    public void saveImageForRecursive(final List<String> img, final int imgSize, final LoadingSaveDialog loadingSaveDialog) {//递归保存
        if (loadingSaveDialog != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    loadingSaveDialog.setLoadingTips("已保存" + (imgSize - img.size() + 1) + "/" + imgSize + "张");
                }
            });

        }
        if (img.size() != 0) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    saveImageToSdCard(getContext(), img.get(0), true);

                    img.remove(0);
                    saveImageForRecursive(img, imgSize, loadingSaveDialog);
                }
            }
            ).start();
        } else {

            if (loadingSaveDialog != null) {
                loadingSaveDialog.dismiss();
            }
            Looper.prepare();
            String fileName;
            if (Build.BRAND.equals("Xiaomi")) { // 小米手机
                fileName = "/DCIM/Camera/";
            } else {  // Meizu 、Oppo
                fileName = "/DCIM/Camera/";
            }
            ToastUtil.initToast(getContext(), "图文保存至" + fileName);

            ToastUtil.initToast(getContext(), "图文保存成功！快去发朋友圈推广吧~");
            Looper.loop();
        }

    }

    // 必须实现，这里返回您的contentView
    // 为了让库更加准确的做出适配，强烈建议使用createPopupById()进行inflate
    @Override
    public View onCreateContentView() {
        return createPopupById(R.layout.share_pop);
    }


    private AnimationSet mAnimationSet;

    private void buildAnima() {
        ScaleAnimation mScaleAnimation = new ScaleAnimation(1f, 2f, 1f, 2f, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        mScaleAnimation.setDuration(200);
        mScaleAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
        mScaleAnimation.setFillAfter(false);

        AlphaAnimation mAlphaAnimation = new AlphaAnimation(1, .2f);
        mAlphaAnimation.setDuration(400);
        mAlphaAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
        mAlphaAnimation.setFillAfter(false);

        mAnimationSet = new AnimationSet(false);
        mAnimationSet.setDuration(400);
        mAnimationSet.addAnimation(mScaleAnimation);
        mAnimationSet.addAnimation(mAlphaAnimation);
        mAnimationSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dismiss();
                    }
                }, 150);

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }


    @Override
    protected Animation onCreateShowAnimation() {
        Animation showAnima = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,
                0,
                Animation.RELATIVE_TO_PARENT,
                0,
                Animation.RELATIVE_TO_PARENT,
                1f,
                Animation.RELATIVE_TO_PARENT,
                0);
        showAnima.setInterpolator(new DecelerateInterpolator());
        showAnima.setDuration(10);
        return showAnima;
    }

    @Override
    protected Animation onCreateDismissAnimation() {
        Animation exitAnima = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,
                0f,
                Animation.RELATIVE_TO_PARENT,
                0,
                Animation.RELATIVE_TO_PARENT,
                0,
                Animation.RELATIVE_TO_PARENT,
                1f);
        exitAnima.setInterpolator(new DecelerateInterpolator());
        exitAnima.setDuration(10);
        return exitAnima;
    }


    //根据网络图片url路径保存到本地
    public final File saveImageToSdCard(Context context, String image, boolean isxiangce) {
        boolean success = false;
        File file = null;
        try {
            if (isxiangce) {
                file = createXiangCeImageFile(context);
            } else {
                file = createStableImageFile(context);

            }

            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);

            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));//path_export是你导出的文件路径


        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {
            return file;
        } else {
            return null;
        }
    }

    //创建相册
    public static File createXiangCeImageFile(Context context) throws IOException {
        String imageFileName = IMAGE_NAME + System.currentTimeMillis() + ".jpg";

        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        } else {  // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        }
        file = new File(fileName);

        if (file.exists()) {
            file.delete();
        }
        return file;
    }

    //创建本地保存路径
    public static File createStableImageFile(Context context) throws IOException {

        i++;
        String imageFileName = IMAGE_NAME + System.currentTimeMillis() + ".jpg";
        File storageDir = context.getExternalCacheDir();
        File image = new File(storageDir, imageFileName);
        return image;
    }

    //创建本地保存路径 小程序
    public static File createStableImageFileXCX(Context context) throws IOException {

        xcXimageFileName = System.currentTimeMillis() + ".jpg";
        File storageDir = context.getExternalCacheDir();
        File image = new File(storageDir, xcXimageFileName);
        return image;
    }

    public static void shareXCX(AllPostersEntity.BodyBean.ShareBean shareBean) {

        File externalCacheDir = AppContext.getInstance().getExternalCacheDir();
        String fileName = externalCacheDir.getPath() + "/" + xcXimageFileName;


        WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
        miniProgramObj.webpageUrl = shareBean.getLink(); // 兼容低版本的网页链接
/*
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
*/
        miniProgramObj.userName = shareBean.getMiniAppId();     // 小程序原始id
        miniProgramObj.path = shareBean.getPath();            //小程序页面路径
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        msg.title = shareBean.getTitle();                 // 小程序消息title
        msg.description = shareBean.getDesc();
        Bitmap bitmap = BitMapUtil.getBitmap(fileName);

        msg.thumbData = BitMapUtil.compressBitmap(bitmap, 100 * 1024);// 小程序消息desc

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage";
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前支持会话
        IWXAPI api = WXAPIFactory.createWXAPI(AppContext.getInstance(), Constant.ID.WeChat_APP_ID, false);

        api.sendReq(req);
    }

    private void shareXText(int i, AllPostersEntity.BodyBean shareBean) {//0 聊天1 朋友圈 其他收藏

        WXTextObject miniProgramObj = new WXTextObject(shareBean.getDescription());
/*
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
*/
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        msg.description = shareBean.getDescription();
        //Bitmap bitmap = BitMapUtil.getBitmap(fileName);


        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "text";
        req.message = msg;
        req.scene = i == 0 ? SendMessageToWX.Req.WXSceneSession : i == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneFavorite;
        IWXAPI api = WXAPIFactory.createWXAPI(getContext(), Constant.ID.WeChat_APP_ID, false);

        api.sendReq(req);
    }

    private void share(int i, AllPostersEntity.BodyBean.ShareBean shareBean) {

        String imageFileName = shareBean.getImageUrl();
        File externalCacheDir = activity.getExternalCacheDir();
        String fileName = externalCacheDir.getPath() + "/" + imageFileName;
        String sharefileName = externalCacheDir.getPath() + "/12306" + imageFileName;


        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = shareBean.getLink();
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = shareBean.getTitle();
        msg.description = shareBean.getDesc();
        Bitmap bitmap = BitMapUtil.getBitmap(fileName);
        /*Bitmap bitmap1 = BitMapUtil.compressBitmap(bitmap, 31*1024);
        BitMapUtil.saveBitmap2File(bitmap1,sharefileName);
        Bitmap bitmap2 = BitMapUtil.getBitmap(sharefileName);*/
        //Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.share);
        msg.thumbData = BitMapUtil.compressBitmap(bitmap, 31 * 1024);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage";
        req.message = msg;
        req.scene = i == 0 ? SendMessageToWX.Req.WXSceneSession : i == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneFavorite;
        IWXAPI api = WXAPIFactory.createWXAPI(activity, Constant.ID.WeChat_APP_ID, false);
        api.sendReq(req);

    }

    //根据网络图片url路径保存到本地
    public static File   saveImageToSdCardXCX(Context context, String image) {
        boolean success = false;
        File file = null;
        try {

            file = createStableImageFileXCX(context);

            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);

            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), image, file.getName(), "你对图片的描述");

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {

            return file;
        } else {
            return null;
        }
    }


    public void setPictureClickCallback(VipDynamicListAdapter.Callback callback) {
        mCallback = callback;
    }


    @Override
    public void onPictureLongPress(ImageView v, String url, int pos) {

    }

    @Override
    public void onThumbPictureClick(int positopn, ImageView i, List<ImageView> imageGroupList, List<String> urlList) {
        vImageWatcher.show1(positopn, i, imageGroupList, urlList);

        dismiss();

    }

    public interface Callback {
        void onThumbPictureClick(int positopn, ImageView i, List<ImageView> imageGroupList, List<String> urlList);
    }


}


